package com.gx.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.gx.common.enums.ResultCodeEnum;
import com.gx.common.exception.CommonException;
import com.gx.utils.DataSourceThreadLocal;
import com.gx.utils.TenantThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author lpj
 */
@Component
@Slf4j
public class TenInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String tenId = request.getHeader("ten-id");
        if (StrUtil.isBlankOrUndefined(tenId)) {
            throw new CommonException(ResultCodeEnum.PARAM_REQUIRE);
        }
        TenantThreadLocal.set(tenId);
        return true;
    }

    /**
     * 完成后执行,删除本地线程中的用户id
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) {
        //清空本地线程
        DataSourceThreadLocal.removeDataSource();
        TenantThreadLocal.remove();
    }
}


